//
//  DatePickerViewController.m
//  MoneyLog
//
//  Created by LogicTech on 3/25/11.
//  Copyright 2011 wicresoft. All rights reserved.
//

#import "DatePickerViewController.h"


@implementation DatePickerViewController
@synthesize datePicker;
@synthesize titleString;
@synthesize contentText;
@synthesize myViewDelegate;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [datePicker release];
    [titleString release];
    [contentText release];
    [myViewDelegate release];
    [contentLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.title =titleString;
    contentText=[[NSString alloc] init];
    
    UIBarButtonItem* saveItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                              target:self
                                                                              action:@selector(saveAction:)];
	self.navigationItem.rightBarButtonItem = saveItem;
	[saveItem release];
    
    //使DatePicker可以滚动
    self.tableView.canCancelContentTouches=NO;
    self.tableView.delaysContentTouches=NO;
    
    datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
	datePicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    datePicker.timeZone =[NSTimeZone systemTimeZone];
    datePicker.locale = [NSLocale currentLocale];
	datePicker.datePickerMode = UIDatePickerModeDateAndTime; 
	
	// note we are using CGRectZero for the dimensions of our picker view,
	// this is because picker views have a built in optimum size,
	// you just need to set the correct origin in your view.
	//
	// position the picker at the bottom
	CGSize pickerSize = [datePicker sizeThatFits:CGSizeZero];
	datePicker.frame = [self pickerFrameWithSize:pickerSize];
    
    [datePicker addTarget:self action:@selector(onTimerValueChanged) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:datePicker];
    
    UISegmentedControl *segmented =[[UISegmentedControl alloc] initWithFrame:CGRectMake(60, 40, 200, 44)];
    [segmented insertSegmentWithTitle:@"时间" atIndex:0 animated:YES];
    [segmented insertSegmentWithTitle:@"日期" atIndex:1 animated:YES];
    segmented.segmentedControlStyle = UISegmentedControlStylePlain;
    [segmented addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    [segmented setSelectedSegmentIndex:0];
    [self.view addSubview:segmented];
    [segmented release];
    
    contentLabel=[[UILabel alloc] initWithFrame:CGRectMake(40, 110, 240, 50)];
    [contentLabel setFont:[UIFont  fontWithName:@"Helvetica-Oblique"  size:20]];
    contentLabel.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:contentLabel];
    
    [self onTimerValueChanged];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    [cell.contentView addSubview:contentLabel];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma 创建DatePicker区域
- (CGRect)pickerFrameWithSize:(CGSize)size
{
	CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
	CGRect pickerRect = CGRectMake(	0.0,
                                   screenRect.size.height - size.height,
                                   size.width,
                                   size.height);
	return pickerRect;
}

/*
- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view {
    if ([view isKindOfClass:[UIDatePicker class]] ) {
        //|| [view isKindOfClass:[UIPicker class]]
        return YES;
    }
    
    return [self touchesShouldBegin:touches withEvent:event inContentView:view];
}

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
    if ([view isKindOfClass:[UIDatePicker class]] ) {
        return NO;
    }
    
    return [self touchesShouldCancelInContentView:view];
}
 */

#pragma DatePicker事件响应
-(void) onTimerValueChanged{
    //格式化日期
	NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    
    [dateFormatter setTimeStyle:kCFDateFormatterFullStyle];
    [dateFormatter setDateStyle:kCFDateFormatterFullStyle];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    contentLabel.text=[dateFormatter stringFromDate:datePicker.date]; 
    
    [self.tableView reloadData];
    [dateFormatter release];
}

- (void)saveAction:(id)sender
{
	// finish typing text/dismiss the keyboard by removing it as the first responder
    [myViewDelegate myView:self.view id:datePicker.date];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction) segmentedAction:(id)sender {
    UISegmentedControl *control = (UISegmentedControl *)sender;
    if ([control selectedSegmentIndex]==1) {
        datePicker.datePickerMode = UIDatePickerModeDate;
    }
    else
    {
        datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    }
}

@end
